import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lz_app_core/kd_user/kd_user_info.dart';
import 'package:lz_app_core/utils/kd_storage.dart';
import 'package:lz_login/src/serve/kd_login_api.dart';
import 'package:lz_login/src/serve/models/kd_go_page.dart';
import 'package:lz_login/src/widgets/kd_user_protocal_widget.dart';
import 'package:lz_router/kd_router.dart';
import 'package:lz_ui/kd_ui.dart';
import '../../kd_login.dart';
import '../widgets/kd_login_bottom_tel.dart';
import '../widgets/kd_verification_code.dart';
import 'package:lz_app_core/extension/kd_extension.dart';
import 'package:lz_app_core/constants/app_manager.dart';
import 'package:lz_base/kd_base.dart';

class KDLoginPage extends StatefulWidget {
  const KDLoginPage({super.key});

  @override
  State<KDLoginPage> createState() => _KDLoginPageState();
}

class _KDLoginPageState extends State<KDLoginPage> {
  /// 电话有误
  var phoneErr = false.obs;

  /// 密码是否有误
  var pwdErr = false.obs;

  /// 是否是验证登录
  var isCodeLogin = false.obs;

  /// 是否已经点击获取验证码
  bool hasGetCode = false;

  TextEditingController phoneController = TextEditingController();
  TextEditingController pwdController = TextEditingController();

  /// 用户输入
  String _phone = '';
  String _code = '';
  String _pwd = '';
  bool checkProtocal = false;
  bool isShowProtocal = Platform.isAndroid || Platform.isIOS;
  @override
  void initState() {
    super.initState();

    _phone = KDStorage.get<String>(KDStorageKey.phone.name) ?? '';
    _pwd = KDStorage.get<String>(KDStorageKey.pwd.name) ?? '';
    phoneController.text = _phone;
    pwdController.text = _pwd;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context,
        designSize: const Size(750, 1336), minTextAdapt: true);
    return KDScaffold.scaffold(
        titleWidget: Text(
          "登录",
          style: TextStyle(
              color: Colors.black,
              fontSize: KD.font(32),
              fontWeight: FontWeight.w500),
        ),
        leading: Container(),
        body: SafeArea(
          child: Padding(
            padding: EdgeInsets.all(KD.size(32)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ECSegmentWidget(
                  const ["密码登录", "短信登录"],
                  didSelectIndex: (index) {
                    isCodeLogin.value = index == 1;
                  },
                  config: KDSegmentConfig()
                    ..bottomStyle = KDSegmentBottomStyle.text,
                ),
                SizedBox(height: KD.space),
                Obx(() => KDAccountPwdWidget(
                      title: "手机号",
                      error: "请输入正确手机号",
                      isErr: phoneErr.value,
                      textController: phoneController,
                      onChange: (input) {
                        _phone = input;
                        phoneErr.value = input.length == 11 && !input.isPhone;
                      },
                    )),
                Obx(() => isCodeLogin.value ? _codeInput : _pwdInput),
                Obx(() =>
                    Visibility(visible: !isCodeLogin.value, child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        GestureDetector(
                            onTap: _forgetPwd,
                            child: Text(
                              "忘记密码",
                              style: TextStyle(
                                  fontSize: KD.font(32), color: KDColor.main),
                            ))
                      ],
                    ),)),
                _space(height: 24),
                KDBgWidget(
                  height: KD.size(80),
                  bgColor: KDColor.main,
                  margin: EdgeInsets.zero,
                  onTap: _login,
                  child: Center(
                    child: Text(
                      "登录",
                      style:
                          TextStyle(color: Colors.white, fontSize: KD.font(32)),
                    ),
                  ),
                ),
                _space(height: isShowProtocal ? 16 : 0),
                Visibility(
                  visible: isShowProtocal,
                  child: KDUserProtocalWidget(
                    value: checkProtocal,
                    checkCall: (e) => checkProtocal = e,
                  ),
                ),
                Visibility(
                  visible: !AppManager.appName.isOwner,
                  child: Center(
                    child: TextButton(
                        onPressed: _register,
                        child: Text(
                          "注册新用户",
                          style: TextStyle(
                              fontSize: KD.font(32), color: KDColor.main),
                        )),
                  ),
                ),
                Visibility(
                  visible: !AppManager.isRelease,
                  child: Center(
                    child: TextButton(
                        onPressed: _changeApp,
                        child: Text(
                          ".      .",
                          style: TextStyle(
                              fontSize: KD.font(32), color: KDColor.main),
                        )),
                  ),
                ),
                const Flexible(
                    child: Align(
                  alignment: Alignment.bottomCenter,
                  child: KDTelWidget(),
                ))
              ],
            ),
          ),
        ));
  }

  /// 验证码登录
  Widget get _codeInput => KDVerificationCodeWidget(
        phoneCall: () => _phone,
        type: 0,
        hasGetCode: (p0) => hasGetCode = p0,
        inputCode: (p0) {
          _code = p0;
        },
      );

  /// 密码
  Widget get _pwdInput {
    return Obx(() => KDAccountPwdWidget(
        title: "密码",
        error: "请输入大于10位数密码或使用数字、字母、特殊字符号组合",
        isPwd: true,
        isErr: pwdErr.value,
        onChange: (input) {
          _pwd = input;
        },
        textController: pwdController));
  }

  /// 按照dp
  Widget _space({double height = 16}) => SizedBox(
        height: KD.size(height),
      );

  /////// -vm
  /// 注册
  _register() {
    KDRouter.to(KDLoginRouter.register);
  }

  /// 登录
  _login() async {
    bool err = false;
    if (!_phone.isPhone) {
      phoneErr.value = true;
      err = true;
      return;
    }

    if (_pwd.length < 6 && !isCodeLogin.value) {
      pwdErr.value = true;
      err = true;
      return;
    }
    pwdErr.value = false;
    phoneErr.value = false;

    if (isCodeLogin.value) {
      if (!hasGetCode) {
        DialogUtils.showToast("请先获取验证码");
        return;
      }

      if (hasGetCode && _code.length != 4) {
        DialogUtils.showToast(_code.isEmpty ? "请先输入验证码" : "验证码格式不对");
        return;
      }
    }
    // 隐私协议
    if (!checkProtocal && isShowProtocal) {
      DialogUtils.showToast("请先勾选《用户服务协议》及《隐私政策》");
      return;
    }

    bool loginSuccess = false;
    if (isCodeLogin.value) {
      loginSuccess = await KDLoginApi.codeLogin(phone: _phone, code: _code);
    } else {
      loginSuccess = await KDLoginApi.login(phone: _phone, pwd: _pwd);
    }

    if (loginSuccess) {
      // KDLoginManager.bindJPush();

      /// 发送登陆成功的通知
      eventBus.fire(KDLoginInSuccess());

      // 具体进入那个页面 当前状态：1-未订购角色，2-有未提交认证，到认证页面，
      // 3-必提交认证已提交，到首页，4-未订购角色，第一个认证信息已提交，
      // 5-跳到首页，未签署免签协议，6-跳到首页，未绑定车辆
/*
    不同用户角色
    1-弹订购。未订购角色1。 18095520859
    2-到认证页。有未提交认证。13003609955、13003609970
    3-跳到首页。必提交认证已提交，到首页。15280808989
    4-弹订购。未订购角色4，第一个认证信息已提交，签订认购后跳转到首页。15288350000
    5-跳到首页。未签署免签协议
    6-跳到首页。未绑定车辆。
 */
      KDGoPage? to = await KDLoginApi.getGoPage();
      // to = KDGoPage(memberRoleName: 'test',status: 3);

      if (AppManager.isOwner) {
        bool success = await KDLoginApi.getCorpInfo();
      } else {
      }

      if (to != null) {
        switch (to.status) {
          case 1:
            _order(to.memberRoleName, 1);
            break;
          case 2:
            eventBus.fire(KDCertificationEvntBusModel(false));
            break;
          case 3:
          case 5:
          case 6:
            KDRouter.toTabbar();
            break;
          case 4:
            _order(to.memberRoleName, 4);
            break;
        }
      }
    }
  }

  _order(String? appName, int state) {
    appName ??= AppManager.appName.name;
    KDAlert.alertCheck(context,
        title: "手机号码已经是蓝智科技会员用户，请问您是否确认要成为$appName会员",
        subWidget: KDUserProtocalWidget(
          checkCall: (bool) {},
          showcheck: false,
        ), confirm: () {
      if (state == 1) {
        eventBus.fire(KDCertificationEvntBusModel(false));
        return;
      }

      // 4
      KDLoginApi.miniConfirmRole().then((value) {
        if (value == 2) {
          // 到订购角色
          eventBus.fire(KDCertificationEvntBusModel(false));
        } else if (value == 3) {
          KDRouter.toTabbar();
        }
      });
    });
  }

  /// 忘记密码
  _forgetPwd() {
    KDRouter.to(KDLoginRouter.forgetPwd, arguments: {"phone": _phone});
  }

  _changeApp() {
    KDRouter.to(KDLoginRouter.test);
  }
}
